<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件驱动演示</title>
</head>
<body>
<h1>发送消息到后端</h1>
<input type="text" id="messageInput" placeholder="输入消息" />
<button onclick="sendMessage()">发送</button>

<h2>AI 回复1：</h2>
<div id="aiResponse">等待 AI 回复...</div>

<script>
    const socket = new WebSocket("ws://localhost:3000");

    // WebSocket 错误处理
    socket.onerror = function(error) {
        console.error("WebSocket Error:", error);
    };

    // WebSocket 接收到消息时的处理
    socket.onmessage = function(event) {
        console.log("Message received from server:", event.data);
        document.getElementById("aiResponse").innerText = "AI 回复：" + event.data;
    };

    // 发送消息到后端
    function sendMessage() {
        const msg = document.getElementById("messageInput").value;
        fetch("http://localhost:8080/api/send?message=" + encodeURIComponent(msg), {
            method: "POST"
        })
            .then(res => res.text())
            .then(response => {
                console.log("Message sent:", response);
                alert(response);
            })
            .catch(console.error);
    }
</script>
</body>
</html>
